$(function() {
	"use strict";
	
	var initGoodsTable = function () {

        var table = $('#goods_table');

        table.DataTable({
        	"searching": false,
            "language": {
                "emptyTable": "暂无数据",
                "loadingRecords": "请稍候 - 数据加载中...",
                "info": "显示 _START_ 到 _END_ 共 _TOTAL_ 条记录",
                "infoEmpty": "",
                "infoFiltered": "",
                "lengthMenu": "_MENU_",
                "zeroRecords": "暂无数据",
                "paginate": {
                    "previous":"上一页",
                    "next": "下一页",
                    "last": "最后一页",
                    "first": "第一页"
                }
            },
            "ordering": false,
            "lengthChange":false,
            "pageLength": 20,
            "pagingType": "full_numbers",
            "serverSide": true,
            "ajax": {
                url: context+"/app/goods/list",
                type: 'POST',
                data:function(d){
                	d.userId = $("input[name='userId']").val();
                	var queryForm = $(table.data("queryForm"));
                	var x=queryForm.serializeArray();
            	    $.each(x, function(i, field){
            		 d[field.name] = field.value;
            	    });
                },
                dataSrc: 'goodsList'
            },
            "columns": [
                { "data": "code" },
                { "data": "name" },
                { "data": "price" },
                { "data": "stock" },
                { "data": "freePost",
                    "render": function ( data, type, full, meta ) {
                  	  if(data==0)
                  		  return '否';
                  	  if(data==1)
                  		  return '是';
  	            	return '';
  	              }
                },
                { "data": "id",
  	              "render": function ( data, type, full, meta ) {
  	            	return '<a href="javascript:;" class="btn btn-default btn-sm img-detail" data-goods-id='+data+' data-type="0"><i class="fa fa-image"></i> 轮播图片 </a>';
  	              }	
                },
                { "data": "id",
	              "render": function ( data, type, full, meta ) {
	            	return '<a href="javascript:;" class="btn btn-default btn-sm img-detail" data-goods-id='+data+' data-type="1"><i class="fa fa-image"></i> 详情图片 </a>';
	              }	
                },
                { "data": "status",
                  "render": function ( data, type, full, meta ) {
                	  if(data==0)
                		  return '未发布';
                	  if(data==1)
                		  return '已发布';
	            	return '';
	              }
                },
                { "data": "weight" },
                { "data": "id",
                  "width":280,
                  "render": function ( data, type, full, meta ) {
                	var str='';
                	if(full.status==0){
                		str = str+'<a href="javascript:;" class="btn btn-default btn-sm edit" data-edit-id='+data+'><i class="fa fa-edit"></i> 编辑商品 </a>&nbsp;'+
                 	   '<a href="javascript:;" class="btn btn-danger btn-sm remove" data-remove-id="'+data+'"><i class="fa fa-remove"></i> 删除商品 </a>&nbsp;'+
                 	   '<a href="javascript:;" class="btn btn-info btn-sm publish" data-publish-id="'+data+'"><i class="fa fa-share"></i> 发布商品 </a>&nbsp;';
                	}else if(full.status==1){
                		str = str+'<a href="javascript:;" class="btn btn-danger btn-sm cancel" data-cancel-id='+data+'><i class="fa fa-reply"></i> 撤销商品 </a>&nbsp;'+
                		'<a href="javascript:;" class="btn btn-success btn-sm qrcode" data-goods-id='+data+'><i class="fa fa-qrcode"></i> 获取二维码 </a>&nbsp;';
                	}
                    return str;
                  }
                }
            ]
        });
    }
	
	var initAddGoods = function(){
		$(".addGoods").on('click',function(){
			var dialog = $("#goodsAddDialog");
			var form = $("#goodsForm",dialog);
			form[0].reset();
			dialog.modal();
		});
		
		$(".ok","#goodsAddDialog").on('click',function(){
			var dialog = $("#goodsAddDialog");
			var form = $("#goodsForm",dialog);
			
			App.blockUI({
                target: '#goodsAddDialogContent',
                boxed: true,
                message: '数据处理中...'
            });
			
			$.ajax({
	            url:context+'/app/goods/save',
	            type:'POST',
	            data:form.serialize(),
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	            	App.unblockUI('#goodsAddDialogContent');
	                if(data.id){
	                	toastr["info"]("保存商户成功", "提示");
	                	$('#goods_table').DataTable().draw(false);
	                	dialog.modal('hide');
	                }else{
	                	toastr["error"]("保存商户异常", "提示");
	                }
	                
	            }
	        });
		});
	}
	
	var initEditGoods = function(){
		$("#goods_table").delegate('.edit','click',function(){
			
			var editId = $(this).data("editId");
			
			$("#goodsEditForm")[0].reset();
			var dialog = $("#goodsEditDialog");
			dialog.modal();
			App.blockUI({
                target: '#goodsEditDialogContent',
                boxed: true,
                message: '数据加载中...'
            });
			$.ajax({
	            url:context+'/app/goods/load/'+editId,
	            type:'POST',
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	            	App.unblockUI('#goodsEditDialogContent');
	                if(data.success){
	                	iTsai.form.deserialize($('#goodsEditForm'),data.data)
	                }else{
	                	toastr["error"]("加载商户数据异常", "提示");
	                }
	                
	            }
	        });
			
		});
		
		
		$(".ok","#goodsEditDialog").on('click',function(){
			var dialog = $("#goodsEditDialog");
			var form = $("#goodsEditForm",dialog);
			
			App.blockUI({
                target: '#goodsEditDialogContent',
                boxed: true,
                message: '数据处理中...',
                textOnly: true
            });
			
			$.ajax({
	            url:context+'/app/goods/save',
	            type:'POST',
	            data:form.serialize(),
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	            	App.unblockUI('#goodsEditDialogContent');
	                if(data.id){
	                	toastr["info"]("保存商户成功", "提示");
	                	$('#goods_table').DataTable().draw(false);
	                	dialog.modal('hide');
	                }else{
	                	toastr["error"]("保存商户异常", "提示");
	                }
	                
	            }
	        });
		});
	}
	
	var initRemoveGoods = function(){
		$("#goods_table").delegate('.remove','click',function(){
			
			var removeId = $(this).data("removeId");
			
			$.ajax({
	            url:context+'/app/goods/delete/'+removeId,
	            type:'POST',
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	                if(data.success){
	                	toastr["info"]("删除商户成功", "提示");
	                	$('#goods_table').DataTable().draw(false);
	                }else{
	                	toastr["error"]("删除商户异常", "提示");
	                }
	                
	            }
	        });
			
		});
	}
	
	var initQueryBtn = function(){
		$(".query").on('click',function(){
			var tableId = $(this).data("table");
			var table = $(tableId).DataTable();
			if(table){
				table.draw(false);
			}
		});
	}
	
	var initGoodsImg = function(){
		$("#goods_table").delegate('.img-detail','click',function(){
			var goodsId = $(this).data('goodsId');
			var type = $(this).data('type');
			var uploadObject = $("input[name='x:uploadobject']","#fileupload").val();
			$("input[name='key']","#fileupload").val("pay/upload/"+uploadObject+"/"+goodsId+"/"+type+"/${filename}");
			$("input[name='x:objectid']","#fileupload").val(goodsId);
			$("input[name='x:type']","#fileupload").val(type);
			$("#goodsImgDialog").modal();
			
			
			// Load & display existing files:
			$(".files",'#fileupload').html('');
            $('#fileupload').addClass('fileupload-processing');
            $.ajax({
                url: context+'/app/goods/imgs/'+goodsId+'/'+type,
                type:'POST',
                dataType: 'json',
                context: $('#fileupload')[0]
            }).always(function () {
                $(this).removeClass('fileupload-processing');
            }).done(function (result) {
                $(this).fileupload('option', 'done')
                .call(this, $.Event('done'), {result: result});
            });
			
		});
	}
	
	var initGoodsQrcode = function(){
		$("#goods_table").delegate('.qrcode','click',function(){
			var goodsId = $(this).data('goodsId');
			
			App.startPageLoading({animate: true});
			
			$.ajax({
	            url:context+'/app/goods/qrcode/'+goodsId,
	            type:'POST',
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	            	App.stopPageLoading();
	                if(data.success){
	                	var dialog = $("#goodsQrcodeDialog");
	                	$(".modal-body",dialog).html('<img src="'+data.qrcodeUrl+'"></img>');
	                	dialog.modal();
	                }else{
	                	toastr["error"]("获取商品二维码异常："+data.message, "提示");
	                }
	                
	            }
	        });
			
		});
	}
	
	var initPublishGoods = function(){
		$("#goods_table").delegate('.publish','click',function(){
			var goodsId = $(this).data('publishId');
			
			App.blockUI({
                boxed: true,
                message: '商品发布中...'
            });
			
			$.ajax({
	            url:context+'/app/goods/publish/'+goodsId,
	            type:'POST',
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	            	App.unblockUI();
	            	if(data.success){
	            		toastr["info"]("商品发布成功", "提示");
	            		$('#goods_table').DataTable().draw(false);
	            	}else{
	            		toastr["error"]("商品发布异常"+data.message, "提示");
	            	}
	            }
	        });
			
		});
	}
	
	var initCancelGoods = function(){
		$("#goods_table").delegate('.cancel','click',function(){
			var goodsId = $(this).data('cancelId');
			App.blockUI({
                boxed: true,
                message: '商品撤销中...'
            });
			
			$.ajax({
	            url:context+'/app/goods/cancel/'+goodsId,
	            type:'POST',
	            dataType:'json',
	            success:function(data,textStatus,jqXHR){
	            	App.unblockUI();
	            	if(data.success){
	            		toastr["info"]("商品撤销成功", "提示");
	            		$('#goods_table').DataTable().draw(false);
	            	}else{
	            		toastr["error"]("商品撤销异常"+data.message, "提示");
	            	}
	            }
	        });
			
		});
	}
	
	
	var formUploadInit = function(){
		$.ajax({
            url:context+'/tp/alioss/postobject',
            type:'POST',
            dataType:'json',
            success:function(data,textStatus,jqXHR){
            	iTsai.form.deserialize($('#fileupload'),data)
            	
            	
            	$('#fileupload').attr('action',data.host);
            	
            	$('#fileupload').fileupload({
             	    paramName:'file',
                    disableImageResize: false,
                    autoUpload: false,
                    maxFileSize: 5000000,
                    acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
                    // Uncomment the following to send cross-domain cookies:
                    //xhrFields: {withCredentials: true},                
                }).bind('fileuploadsubmit',function(e,data){
             	   $("input[name='x:filename']","#fileupload").val(data.files[0].name);
                });
            	
            }
        });


   
	}

	initGoodsTable();
	initAddGoods();
	initEditGoods();
	initRemoveGoods();
	initQueryBtn();
	formUploadInit();
	initGoodsImg();
	initPublishGoods();
	initCancelGoods();
	initGoodsQrcode();
});